import { DistanceLine, DistanceLineType } from './DistanceLine';
import { MeasureChildObject } from './ChildObject';
import {
  DistanceLabelPositions,
  MeasureDistanceResultWithLabel,
} from './types';

export class MeasureDistanceObj extends MeasureChildObject {
  lines: DistanceLine[];

  constructor(
    measureResult: MeasureDistanceResultWithLabel,
    distanceType: 'min' | 'center',
    onlyFullDistance = false,
  ) {
    super();

    const lines = [
      new DistanceLine(measureResult, DistanceLineType.Full, distanceType),
      measureResult.xValue > 1e-12 && !onlyFullDistance
        ? new DistanceLine(measureResult, DistanceLineType.X, distanceType)
        : null,
      measureResult.yValue > 1e-12 && !onlyFullDistance
        ? new DistanceLine(measureResult, DistanceLineType.Y, distanceType)
        : null,
      measureResult.zValue > 1e-12 && !onlyFullDistance
        ? new DistanceLine(measureResult, DistanceLineType.Z, distanceType)
        : null,
    ];

    this.lines = lines.filter(Boolean);

    if (this.lines.length === 2) {
      this.lines = [this.lines[0]];
    }

    this.lines.forEach((l) => this.add(l));
  }

  destroy() {
    (this.children as DistanceLine[]).forEach((c) => c.destroy());
    this.parent?.remove(this);
  }

  setHover(val: boolean): void {
    super.setHover(val);
    this.lines.forEach((l) => l.setHover(val));
  }

  setSelect(val: boolean): void {
    super.setHover(val);
    this.lines.forEach((l) => l.setSelect(val));
  }

  getLabelPositions() {
    const result = {} as any as DistanceLabelPositions;
    this.lines.forEach((line) => {
      if (line.type === DistanceLineType.Full) {
        result.full = line.label.endPosition.toArray();
      }
      if (line.type === DistanceLineType.X) {
        result.x = line.label.endPosition.toArray();
      }
      if (line.type === DistanceLineType.Y) {
        result.y = line.label.endPosition.toArray();
      }
      if (line.type === DistanceLineType.Z) {
        result.z = line.label.endPosition.toArray();
      }
    });

    return result;
  }
}
